<script setup>
import { ref, computed } from "vue";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { userAnswerApi } from "@/api/userAnswer";
import { optionCategoryApi } from "@/api/optionCategory";
import { useQuestionnaireGroup } from "@/composables/useQuestionnaireGroup.js";

const optionCategories = ref([]);
const initialQuestion = ref();
const isTestFinished = ref(false);
const isStartTest = ref(false);

const token = ref(sessionStorage.getItem("pmp-token"));

const router = useRouter();
const loading = ref(false);

// 使用 watchEffect 监听 sessionStorage 变化
watchEffect(() => {
  // 监听 storage 事件，当其他标签页或窗口修改了 sessionStorage 时也能感知到
  const handleStorageChange = (e) => {
    if (e.key === 'pmp-token') {
      console.log('检测到 token 变化:', e.newValue ? '已登录' : '已登出');
      // 手动更新 token 的值
      token.value = e.newValue;
    }
  };
  
  // 监听当前页面的 sessionStorage 变化（通过定时器或自定义事件）
  const checkTokenChange = () => {
    const currentToken = sessionStorage.getItem("pmp-token");
    if (currentToken !== token.value) {
      console.log('检测到当前页面 token 变化:', currentToken ? '已登录' : '已登出');
      token.value = currentToken;
    }
  };
  
  // 定期检查 token 变化（每500ms检查一次）
  const intervalId = setInterval(checkTokenChange, 500);
  
  window.addEventListener('storage', handleStorageChange);
  
  // 清理监听器
  return () => {
    window.removeEventListener('storage', handleStorageChange);
    clearInterval(intervalId);
  };
});

// 使用问卷组管理
const {
  userAnswerGroupId,
  currentQuestionnaireIndex,
  questionnaires,
  currentQuestionnaireId,
  isAllCompleted,
  initQuestionnaireGroup,
  restoreFromStorage,
  markCurrentCompleted,
  nextQuestionnaire,
  getQuestionnaireResult,
  clearAll,
} = useQuestionnaireGroup();

// 计算当前选项分类的索引
const currentCategoryIndex = computed(() => {
  if (!initialQuestion.value?.optionCategoryId) return 0;
  return parseInt(initialQuestion.value.optionCategoryId) - 1;
});

// 获取当前选项分类
const currentCategory = computed(() => {
  return optionCategories.value[currentCategoryIndex.value] || null;
});

// 获取选项的颜色
const getOptionColor = (index) => {
  const colors = ["#88619a", "#88619a", "#dddddd", "#33a474", "#33a474"];
  return colors[index] || "#dddddd";
};

// 获取悬停时的颜色
const getHoverColor = (baseColor) => {
  const hoverColors = {
    "#33a474": "#2a8a5f", // 深绿色
    "#dddddd": "#c0c0c0", // 深灰色
    "#88619a": "#6f4f7d", // 深紫色
  };
  return hoverColors[baseColor] || baseColor;
};

// 获取选项大小
const getOptionSize = (index) => {
  const sizes = ["48px", "40px", "32px", "40px", "48px"];
  return sizes[index] || "32px";
};

const nextQuestion = async (optionId) => {
  if (loading.value) return;
  loading.value = true;
  const params = {
    questionnaireId: currentQuestionnaireId.value,
    questionId: initialQuestion.value.id,
    optionId: optionId,
    userAnswerId: initialQuestion.value.userAnswerId,
    userAnswerGroupId: userAnswerGroupId.value, // 添加问卷组ID
  };
  const res = await userAnswerApi.submitSingleAnswer(params);
  if (res.success) {
    if (res.data === null) {
      // 当前问卷完成
      markCurrentCompleted(initialQuestion.value.userAnswerId);
      initialQuestion.value = null;

      // 检查是否还有下一个问卷
      if (nextQuestionnaire()) {
        // 还有下一个问卷，开始新的问卷
        await startNewQuestionnaire();
      } else {
        // 所有问卷都完成了
        isTestFinished.value = true;
        sessionStorage.setItem("isTestFinished", isTestFinished.value);
      }
    } else {
      initialQuestion.value = res.data;
    }
  }
  loading.value = false;
};

// 开始新的问卷
const startNewQuestionnaire = async () => {
  const res = await userAnswerApi.submitSingleAnswer({
    questionnaireId: currentQuestionnaireId.value,
    userAnswerGroupId: userAnswerGroupId.value,
  });
  if (res.success) {
    initialQuestion.value = res.data;
  } else {
    console.error("开始新问卷失败:", res.message);
  }
};

const goToTestResults = (index) => {
  if (isAllCompleted.value) {
    // 所有问卷都完成，跳转到最终结果页面
    router.push(`/final-results/${userAnswerGroupId.value}`);
  } else {
    // 跳转到当前问卷的结果页面
    const currentUserAnswerId = getQuestionnaireResult(
      questionnaires.value[index].id
    );
    console.log(currentUserAnswerId);

    if (currentUserAnswerId) {
      router.push(`/results/${currentUserAnswerId}`);
    }
  }
};

// 查看最终结果
const viewFinalResults = () => {
  router.push(`/five/final-results/${userAnswerGroupId.value}`);
};

// 重新开始测试
const restartTest = () => {
  clearAll();
  initQuestionnaireGroup();
  isTestFinished.value = false;
  sessionStorage.removeItem("isTestFinished");
  startNewQuestionnaire();
};

const handleStartTest = async () => {
  await startNewQuestionnaire();
  isStartTest.value = true;
  sessionStorage.setItem("isStartTest", isStartTest.value);
};

onMounted(async () => {
  // 加载选项分类
  if (sessionStorage.getItem("option-categories")) {
    optionCategories.value = JSON.parse(
      sessionStorage.getItem("option-categories")
    );
  } else {
    const res = await optionCategoryApi.getAllOptionCategories();
    if (res.success) {
      optionCategories.value = res.data;
      sessionStorage.setItem(
        "option-categories",
        JSON.stringify(optionCategories.value)
      );
    }
  }
  // 恢复问卷组状态
  restoreFromStorage();

  // 检查是否有未完成的测试
  if (sessionStorage.getItem("isTestFinished")) {
    isTestFinished.value = sessionStorage.getItem("isTestFinished") === "true";
  }

  // 如果没有问卷组ID，初始化新的问卷组
  if (!userAnswerGroupId.value) {
    initQuestionnaireGroup();
  }
  
  // 调试信息
  console.log('问卷数据:', questionnaires.value);
  console.log('当前问卷索引:', currentQuestionnaireIndex.value);
});
</script>

<template>
  <div>
    <img
      src="/src/assets/five-bg.jpg"
      alt="test"
      class="object-cover w-full h-full -mt-20"
    />
    <div
      v-if="token"
      class="flex flex-col justify-center items-center gap-12 mt-10"
    >
      <!-- 问卷状态指示器 -->
      <div class="flex justify-center items-center space-x-2">
        <div
          v-for="(questionnaire, index) in questionnaires"
          :key="questionnaire.id"
          class="cursor-pointer flex items-center relative"
        >
          <div
            class="px-4 py-2 rounded-lg text-sm font-medium transition-all duration-300 hover:shadow-md"
            :class="[
              index === currentQuestionnaireIndex
                ? 'bg-blue-500 text-white shadow-lg'
                : questionnaire.completed
                ? 'bg-green-500 text-white'
                : 'bg-gray-200 text-gray-600 hover:bg-gray-300',
            ]"
          >
            {{ questionnaire.type || `问卷${index + 1}` }}
          </div>
          <!-- 连接线 -->
          <div
            v-if="index < questionnaires.length - 1"
            class="w-4 h-0.5 bg-gray-300 ml-2"
          ></div>
        </div>
      </div>

      <div class="flex flex-col justify-center items-center gap-12 mt-10">
        <div class="text-center">
          <div class="text-[26px] text-[#576071]">
            {{ initialQuestion?.title }}
          </div>
        </div>

        <template v-if="isTestFinished">
          <div class="text-center space-y-4">
            <div class="text-lg text-gray-700">恭喜！您已完成所有问卷测试</div>
            <div class="flex space-x-4">
              <Button
                label="查看最终结果"
                icon="pi pi-chart-bar"
                @click="viewFinalResults"
                class="bg-[#33a474] hover:bg-[#2a8a5f] border-[#33a474] hover:border-[#2a8a5f] transition-colors duration-300"
              />
              <Button
                label="重新开始"
                icon="pi pi-refresh"
                severity="secondary"
                @click="restartTest"
                class="transition-colors duration-300"
              />
            </div>
          </div>
        </template>
        <template v-else>
          <Button
            v-if="!isStartTest"
            label="开始测试"
            severity="primary"
            @click="handleStartTest"
            class="transition-colors duration-300"
          />
          
          <template v-else>
            <!-- 选项圆圈 -->
            <div
              v-if="initialQuestion && currentCategory"
              class="flex flex-col"
            >
              <div class="flex items-center gap-20">
                <div class="text-[#88619a] text-2xl font-medium">不同意</div>
                <div
                  v-for="(option, index) in currentCategory.options"
                  :key="option.id"
                  v-tooltip.top="option.label"
                  @click="nextQuestion(option.id)"
                  :class="[
                    'rounded-full cursor-pointer transition-all duration-300 ease-in-out transform hover:scale-110 hover:shadow-lg',
                    loading
                      ? 'opacity-50 cursor-not-allowed'
                      : 'hover:opacity-80',
                  ]"
                  :style="{
                    backgroundColor: getOptionColor(index),
                    width: getOptionSize(index),
                    height: getOptionSize(index),
                    '--hover-color': getHoverColor(getOptionColor(index)),
                  }"
                ></div>
                <div class="text-[#33a474] text-2xl font-medium">同意</div>
              </div>
              <!-- 加载状态 -->
              <div v-if="loading" class="mt-4 text-center">
                <div
                  class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-[#33a474]"
                ></div>
                <span class="ml-2 text-[#576071]">评估中...</span>
              </div>
            </div>
          </template>
        </template>
      </div>
    </div>
    <div v-else class="text-2xl text-center mt-20">
      暂未登录，请您登录后进行测试
    </div>
  </div>
</template>

<style scoped>
/* 悬停效果 */
.rounded-full:hover {
  background-color: var(--hover-color) !important;
}

/* 点击效果 */
.rounded-full:active {
  transform: scale(0.95);
}

/* 禁用状态 */
.rounded-full.cursor-not-allowed:hover {
  transform: none;
  opacity: 0.5 !important;
}

/* 工具提示样式 */
:deep(.p-tooltip) {
  z-index: 1000;
}

:deep(.p-tooltip .p-tooltip-text) {
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  white-space: nowrap;
}

/* 加载动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
